<template>
  <div class="users">
    <!-- 搜索 -->
    <div class="search">
      <!-- 搜索框 -->
      <el-input
        placeholder="请输入内容"
        v-model="search"
        class="input-with-select"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
      <!-- 添加按钮 -->
      <el-button type="primary" @click="addModal">添加按钮</el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="userList" border style="width: 100%">
      <el-table-column prop="username" label="姓名"> </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="role_name" label="角色"> </el-table-column>
      <el-table-column prop="mg_state" label="状态">
        <template slot-scope="scope">
          <el-switch
            @change="updateStatus(scope.row)"
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button size="mini" type="warning" @click="assignRoles(scope.row)"
            >分配角色</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加,编辑的模态框 -->
    <el-dialog
      :title="editId ? '编辑用户' : '添加用户'"
      :visible.sync="addEditModal"
      width="50%"
    >
      <!-- 表单 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="用户名"
          prop="username"
          v-if="editId ? true : false"
        >
          <el-input v-model="ruleForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username" v-else>
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password" v-if="!editId">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addEditModal = false">取 消</el-button>
        <el-button type="primary" @click="addData">{{
          editId ? "编辑用户" : "添加用户"
        }}</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的弹出框 -->
    <el-dialog title="提示" :visible.sync="setRolesModal" width="50%">
      <!-- <span>这是一段信息</span> -->
      <!-- 内容 -->
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="当前用户">
          <template> {{ currentName }} </template>
        </el-form-item>
        <el-form-item label="当前角色">
          <template> {{ currentRoles }} </template>
        </el-form-item>
        <el-form-item label="分配角色">
          <!-- :value="item.id" value的内容就是下拉框的值 -->
          <el-select v-model="form.regin" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesModal = false">取 消</el-button>
        <el-button type="primary" @click="handleAssignRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分页 -->
    <!-- :total 总条目数-->
    <!-- page-size 每页显示条目个数 没有你放多少条数据-->
    <!-- page-sizes 每页显示个数选择器的选项设置-->
    <!-- current-page  当前页数 ，你当前在第几页-->

    <!-- 事件 -->
    <!-- @size-change  每页条数改变的时候触发  -->
    <!-- current-change  当前页改变时候触发 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>
<script>
export default {
  data() {
    return {
      userList: [], //用户集合
      queryInfo: {
        query: "", //查询的参数
        pagenum: 1, //当前页
        pagesize: 5, //每页显示的条数
      },
      total:100,//保存用户总条数
      addEditModal: false, //添加或者编辑的模态框状态
      search: "", //搜索框的内容
      ruleForm: {
        username: "",
        password: "",
        mobile: "",
        email: "",
      },
      rules: {
        username: [],
        password: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 11, max: 11, message: "长度在11字符", trigger: "blur" },
        ],
        email: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
      },
      editId: "", //保存编辑的id
      setRolesId: "", //保存分配角色的id
      setRolesModal: false, //分配角色弹出来的状态
      form: {
        regin: "",
      },
      rolesList: [], //存放所有的角色列表信息
      currentName: "", //保存当前用户
      currentRoles: "", //保存当前角色
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    //   请求用户列表的方法
    getUserList() {
      this.$axios.get("/users", { params: this.queryInfo }).then((res) => {
        console.log(res.data.data.users);
        //   把请求过来的用户列表数据赋值给userList
        this.userList = res.data.data.users;
        // 给total赋值
        this.total = res.data.data.total
        console.log(this.total);
        // 给当前页赋值
        this.queryInfo.pagenum = res.data.data.pagenum

      });
    },
    // 点击添加按钮的方法
    addModal() {
      // 清空保存的编辑id，因为添加的时候没有id
      this.editId = "";
      this.addEditModal = true;
      //   清空表单
      this.ruleForm = {};
    },
    // 请求添加数据的方法
    addData() {
      // 判断有没有editId，如果有就发送编辑的请求，如果没有就发送添加的请求
      if (this.editId) {
        // 编辑
        this.$axios
          .put(`/users/${this.editId}`, {
            email: this.ruleForm.email,
            mobile: this.ruleForm.mobile,
          })
          .then((res) => {
            // console.log(res);
            if (res.data.meta.status == 200) {
              //   编辑成功
              this.$message({
                message: "编辑成功",
                type: "success",
              });
              //   刷新页面，
              this.getUserList();
              //   关闭模态框
              this.addEditModal = false;
            } else {
              //   编辑失败
              this.$message.error("编辑失败");
            }
          });
      } else {
        // 添加
        this.$axios.post("/users", this.ruleForm).then((res) => {
          console.log(res);
          if (res.data.meta.status == 201) {
            //   添加成功
            this.$message({
              message: "添加成功",
              type: "success",
            });
            //   刷新页面，
            this.getUserList();
            //   关闭模态框
            this.addEditModal = false;
          } else {
            //   添加失败
            this.$message.error("添加失败");
          }
        });
      }
    },
    // 点击编辑按钮的方法
    handleEdit(row) {
      console.log(row);
      this.editId = row.id;
      this.addEditModal = true;
      // 回显数据
      this.ruleForm = row;
    },
    // 点击删除的方法
    handleDelete(row) {
      console.log(row);
      // 请求
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 点击确定
          // 发送删除的请求
          this.$axios.delete(`/users/${row.id}`).then((res) => {
            if (res.data.meta.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              //   重新刷新页面
              this.getUserList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          // 点击取消
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //    更新状态的方法
    updateStatus(row) {
      //   console.log(row);
      //   请求更新状态的接口
      this.$axios.put(`/users/${row.id}/state/${row.mg_state}`).then((res) => {
        console.log(res);
        if (res.data.meta.status == 200) {
          this.$message({
            type: "success",
            message: res.data.meta.msg,
          });
          //   重新刷新页面
          this.getUserList();
        } else {
          this.$message.error("状态设置失败");
        }
      });
    },
    // 点击分配角色方法
    assignRoles(row) {
      this.setRolesModal = true;
      console.log(row);
      this.setRolesId = row.id;
      this.currentName = row.username;
      this.currentRoles = row.role_name;
      //   请求角色列表
      this.$axios.get("/roles").then((res) => {
        console.log(res);
        this.rolesList = res.data.data;
        console.log(this.rolesList);
      });
    },
    // 点击分配权限弹出框里面的确定按钮，给后端发送请求
    handleAssignRoles() {
      this.$axios
        .put(`/users/${this.setRolesId}/role`, { rid: this.form.regin })
        .then((res) => {
          console.log(res);
          if (res.data.meta.status == 200) {
            this.$message({
              type: "success",
              message: res.data.meta.msg,
            });
            //   重新刷新页面
            this.getUserList();
            // 关闭模态框
            this.setRolesModal = false
          } else {
            this.$message.error("角色设置失败");
          }
        });
    },
    // 每页条数改变会触发
    handleSizeChange(val){
       console.log(val);
       this.queryInfo.pagesize = val
    //    刷新页面
    this.getUserList()

    },
    // 当前页改变触发
    handleCurrentChange(val){
        console.log(val);
        this.queryInfo.pagenum = val
         //    刷新页面
         this.getUserList()
    },
    // 查询
    handleSearch(){
        // 搜索输入框的值赋值给查询的参数
        this.queryInfo.query = this.search
        // 刷新页面
        this.getUserList()
    }

  },
};
</script>
<style lang="scss" scoped>
.search {
  display: flex;
  width: 500px;
  margin: 20px 0;
  .el-button {
    margin-left: 20px;
  }
}
</style>
